<template>
  <div class="app-container" style="width:100%;height:100%;">
    <el-aside style="padding-right: 10px; padding-left: 15px; padding-top: 0px;float:left;width:20%;background:none;">
      <div class="block" style="width:100%;height:100%;">
        <!-- <el-select v-model="xiangmuId" class="filter-item" placeholder="项目" style="width: 100%" clearable @change="handChange">
          <el-option v-for="item in xmList" :key="item.id" :label="item.xiangmumingcheng" :value="item.id" />
        </el-select> -->
        <el-cascader ref="cascaderHandle" v-model="xiangmuId" style="width:100%;" clearable :options="xmList" :props="optionProps" :show-all-levels="false" @change="change">
          <template slot-scope="{ data }">
            <span @click="clickNode">{{ data.xiangmumingcheng }}</span>
          </template>
        </el-cascader>
        <el-tree
          id="el-tree"
          ref="tree"
          class="filter-tree"
          :data="data2"
          node-key="id"
          :highlight-current="true"
          :props="defaultProps"
          :default-expanded-keys="TreeArr"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          @node-contextmenu="rightClick"
        />
        <div v-show="menu1Visible">
          <ul id="menu1" class="menu1" style="font-size:14px;">
            <li class="menu_item" @click="handleAdd">新增下级目录</li>
          </ul>
        </div>
        <div v-show="menu2Visible">
          <ul id="menu2" class="menu2" style="font-size:14px;">
            <li class="menu_item" @click="handleAdd">新增下级目录</li>
            <li class="menu_item" @click="handleEdit">编辑目录</li>
            <li class="menu_item" @click="handleDisable">删除</li>
          </ul>
        </div>
      </div>
    </el-aside>
    <el-aside style="padding-right: 5px; padding-left: 5px; padding-top: 0px;float:left;width:80%;background:none;">
      <div class="filter-container" style="text-align:center;margin-top:0px;padding-bottom: 0px;">
        <el-button class="filter-item" icon="el-icon-circle-plus-outline" type="primary" @click="add()">新增文档</el-button>
        <el-button class="filter-item" icon="el-icon-edit-outline" type="primary" @click="edit()">编辑文档</el-button>
        <el-button class="filter-item" icon="el-icon-download" type="primary" @click="download()">导出文档</el-button>
        <el-button class="filter-item" icon="el-icon-delete-solid" type="danger" @click="remove()">删除文档</el-button>
        <el-button class="filter-item" icon="el-icon-s-data" type="info" @click="history()">文档历史版本</el-button>
        <el-button class="filter-item" icon="el-icon-warning-outline" type="primary" @click="yulan()">预览</el-button>
      </div>

      <el-table v-show="displayVisible" v-loading="listLoading" :data="numList" :height="tableHeight4" style="width: 100%; overflow:auto;" border>
        <el-table-column type="index" header-align="center" align="center" label="序号" width="80px" />
        <el-table-column header-align="center" align="left" label="操作" width="320px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="hlfp(scope)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="项目名称">
          <template slot-scope="scope">
            <span>{{ scope.row.xmName }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="right" label="文档数量">
          <template slot-scope="scope">
            <span>{{ scope.row.num }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div v-show="displayVisible1" style="width:100%; margin:0 auto;">
        <div>
          <table class="table">
            <tr>
              <td class="title-name">
                <strong>项目:</strong>
              </td>
              <td class="table-content">
                <span>{{ from.xmName }}</span>
              </td>
              <td class="title-name">
                <strong>api名称:</strong>
              </td>
              <td class="table-content">
                <span>{{ from.tableName }}</span>
              </td>
            </tr>
            <tr>
              <td class="title-name">
                <strong>备注:</strong>
              </td>
              <td colspan="3" style="100%">
                <span>{{ from.tableDetailExplain }}</span>
              </td>
            </tr>
            <tr>
              <td class="title-name">
                <strong>内容:</strong>
              </td>
            </tr>
            <tr>
              <td colspan="4" style="98%">
                <span v-html="from.htmlData" />
              </td>
            </tr>
          </table>
        </div>
      </div>

      <el-dialog :visible.sync="dialogAddVisible" width="600px" :show-close="false" append-to-body :title="'新增下级目录'">
        <dialog-add v-if="dialogAddVisible" ref="dialogAdd" :xiangmu="xiangmuId" :classify="classifyId" :visible.sync="dialogAddVisible" />
      </el-dialog>

      <el-dialog :visible.sync="dialogEditVisible" width="600px" :show-close="false" append-to-body :title="'编辑目录'">
        <dialog-edit v-if="dialogEditVisible" ref="dialogEdit" :proid="code" :visible.sync="dialogEditVisible" />
      </el-dialog>

      <el-dialog :visible.sync="addApiVisible" width="1200px" :show-close="false" append-to-body :title="'新增文档'">
        <add-api v-if="addApiVisible" ref="addApi" :classify="classifyId" :xiangmu="xiangmuId" :visible.sync="addApiVisible" />
      </el-dialog>

      <el-dialog :visible.sync="editApiVisible" width="1200px" :show-close="false" append-to-body :title="'编辑文档'">
        <edit-api v-if="editApiVisible" ref="editApi" :proid="classifyId" :visible.sync="editApiVisible" />
      </el-dialog>

      <el-dialog :visible.sync="historyVisible" width="1000px" append-to-body :title="'文档历史记录'">
        <history v-if="historyVisible" ref="history" :history="batchCode" :visible.sync="historyVisible" />
      </el-dialog>

      <el-dialog :visible.sync="downloadVisible" width="400px" :show-close="false" append-to-body :title="'选择目录'">
        <download v-if="downloadVisible" ref="download" :xiangmu="xiangmuId" :visible.sync="downloadVisible" />
      </el-dialog>

      <el-dialog :visible.sync="yulanVisible" width="1200px" append-to-body :title="'预览'">
        <yulan v-if="yulanVisible" ref="yulan" :proid="xiangmuId" :visible.sync="yulanVisible" />
      </el-dialog>

    </el-aside>
  </div>
</template>

<script>
import { getXiangMuList } from '@/api/projectInfo'
import { getInfo, getFileList, remove } from '@/api/shuoMingFile'
import { disabled, getInitialLoading, getAgainLoading } from '@/api/shuoMingCatalog'
import { getDictListByCode } from '@/api/dict'
import { Message, MessageBox } from 'element-ui'
import { tableHeight4 } from '@/utils/tableHeight'

import DialogAdd from '../api/add' // eslint-disable-line no-unused-vars
import DialogEdit from '../api/edit' // eslint-disable-line no-unused-vars
import AddApi from '../api/addApi' // eslint-disable-line no-unused-vars
import EditApi from '../api/editApi' // eslint-disable-line no-unused-vars
import history from '../api/history' // eslint-disable-line no-unused-vars
import download from '../api/downloadByXm' // eslint-disable-line no-unused-vars
import yulan from '../api/yulan' // eslint-disable-line no-unused-vars

export default {
  name: 'Zzjg',
  components: { DialogAdd, DialogEdit, AddApi, EditApi, history, download, yulan },
  mixins: [tableHeight4],
  provide() {
    return {
      getTreeList: this.getTreeList
    }
  },
  data() {
    return {
      TreeArr: [],
      optionProps: {
        value: 'id',
        children: 'children',
        label: 'xiangmumingcheng',
        checkStrictly: false,
        expandTrigger: 'hover'
      },
      IdArr: [],
      displayVisible: false,
      displayVisible1: false,
      listLoading: false,
      total: 0,
      xiangmuId: '',
      numList: [],
      xmList: [],
      userList: [],
      classifyId: '',
      batchCode: '',
      flag: '',
      DATA: null,
      NODE: null,
      objectID: null,
      menu1Visible: false,
      menu2Visible: false,
      dialogAddVisible: false,
      dialogEditVisible: false,
      addApiVisible: false,
      editApiVisible: false,
      historyVisible: false,
      downloadVisible: false,
      yulanVisible: false,
      stateOptions: [],
      data: [],
      data2: [],
      from: {},
      queryPage: {},
      datas: '',
      img1: require('../../../assets/images/Folder-01.png'),
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getList()
    this.getXiangMuList()
    this.getDictList('YW_BASE_STATUS')
  },
  methods: {
    getList() {
      this.displayVisible = true
      this.displayVisible1 = false
      getFileList().then(response => {
        this.numList = response.data
        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    // 提示框
    renderContent: function(h, { node, data, store }) {
      var text = data.name
      if (data.flag === 'ML') {
        if (text.length > 15) {
          return (
            < span >
              < i > <img src={this.img1} style='width: 18px;height: 18px;margin-right:5px;padding-top:1px' /></i>
              <el-tooltip class='item' id='tool' effect='light' popper-class='draw' visible-arrow='false' content={data.name} placement='bottom-start' >
                <span class='style-demo' >{data.name}</span >
              </el-tooltip>
            </span>)
        } else {
          return (
            < span >
              < i > <img src={this.img1} style='width: 18px;height: 18px;margin-right:5px;padding-top:1px' /></i>
              <span class='style-demo' >{data.name}</span >
            </span>
          )
        }
      } else {
        if (text.length > 15) {
          return (
            < span >
              <el-tooltip class='item' id='tool' effect='light' popper-class='draw' visible-arrow='false' content={data.name} placement='bottom-start' >
                <span class='style-demo' >{data.name}</span >
              </el-tooltip>
            </span>)
        } else {
          return (
            < span >
              <span class='style-demo' >{data.name}</span >
            </span>
          )
        }
      }
    },
    hlfp(scope) {
      this.displayVisible = false
      this.displayVisible1 = true
      this.xiangmuId = scope.row.xmId

      // 加载列表
      getInitialLoading({ xmId: scope.row.xmId }).then(response => {
        this.data = response.data

        this.data2 = this.buildTree2(this.data)
        this.data2.forEach(m => {
          this.TreeArr.push(m.id)
        })
        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    getXiangMuList() { // 加载列表
      this.xmList = []

      getXiangMuList(this.queryPage).then(response => {
        this.xmList = this.buildTree(response.data)

        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    buildTree(data) {
      var rdata = []
      for (let i = 0; i < data.length; i++) {
        var e1 = data[i]
        if (e1.parentId === '-1') {
          rdata.push(e1)
        }
        for (let j = 0; j < data.length; j++) {
          var e2 = data[j]
          if (e1.parentId === e2.id) {
            if (!e2.children) {
              e2.children = []
            }
            e2.children.push(e1)
          }
        }
      }
      return rdata
    },
    clickNode($event) {
      $event.target.parentElement.parentElement.firstElementChild.click()
      this.$refs.cascaderHandle.dropDownVisible = false
    },
    change(val) {
      const nodesObj = this.$refs['cascaderHandle'].getCheckedNodes()
      this.data = []
      this.data2 = []
      if (val.length === 2) {
        this.displayVisible = false
        this.xiangmuId = nodesObj[0].data.id
        this.getTreeList(nodesObj[0].data.id)
        this.displayVisible1 = true
      } else {
        this.displayVisible = true
        this.displayVisible1 = false
      }
    },
    getTreeList(code) {
      this.data = []
      // 加载列表
      getInitialLoading({ xmId: code }).then(response => {
        this.data = response.data

        this.data2 = this.buildTree2(this.data)
        this.data2.forEach(m => {
          this.TreeArr.push(m.id)
        })
        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    buildTree2(data) {
      var rdata = []
      for (let i = 0; i < data.length; i++) {
        var e1 = data[i]
        if (e1.parentId === '-1') {
          rdata.push(e1)
        }
        for (let j = 0; j < data.length; j++) {
          var e2 = data[j]
          if (e1.parentId === e2.id) {
            if (!e2.children) {
              e2.children = []
            }
            e2.children.push(e1)
          }
        }
      }
      return rdata
    },
    getDictList(code) {
      getDictListByCode(code).then(response => {
        if (code === 'YW_BASE_STATUS') {
          this.stateOptions = response.data
        }
      })
    },
    getDicName(code, flag) {
      var dict = []
      if (flag === 'YW_BASE_STATUS') {
        dict = this.stateOptions
      }
      for (var i in dict) {
        if (dict[i].code === code) {
          return dict[i].name
        }
      }
    },
    // 右键点击
    rightClick(MouseEvent, object, Node, element) { // 鼠标右击触发事件
      this.DATA = object
      this.NODE = Node

      if (this.NODE.level === 1) {
        this.menu1Visible = true // 显示模态窗口，跳出自定义菜单栏
        this.menu2Visible = false // 显示模态窗口，跳出自定义菜单栏

        var menu1 = document.querySelector('#menu1')
        document.addEventListener('click', this.foo) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
        menu1.style.display = 'block'
        menu1.style.left = MouseEvent.clientX - 0 + 'px'
        menu1.style.top = MouseEvent.clientY - 20 + 'px'
      } else if (this.NODE.level > 1 && this.NODE.level < 3) {
        if (this.NODE.data.flag === 'ML') {
          this.menu1Visible = false // 显示模态窗口，跳出自定义菜单栏
          this.menu2Visible = true // 显示模态窗口，跳出自定义菜单栏

          var menu2 = document.querySelector('#menu2')
          document.addEventListener('click', this.foo) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
          menu2.style.display = 'block'
          menu2.style.left = MouseEvent.clientX - 0 + 'px'
          menu2.style.top = MouseEvent.clientY - 20 + 'px'
        }
      }

      this.classifyId = this.NODE.data.id
      this.xiangmuId = this.NODE.data.xmId
    },
    foo() { // 取消鼠标监听事件 菜单栏
      this.menu1Visible = false
      this.menu2Visible = false
      document.removeEventListener('click', this.foo) // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
    },
    handleNodeClick(data) {
      var dataA = data
      this.from = {}
      this.displayVisible1 = true

      this.classifyId = data.id
      this.xiangmuId = data.xmId
      this.flag = data.flag
      this.batchCode = data.code
      this.parent = data.parentId
      if (this.flag === 'WD') {
        getInfo({ code: data.id }).then(response => {
          this.from = response.data[0]
        }).catch(function() {
        })
      } else {
        if (!this.IdArr.includes(dataA.id)) {
        // 树
          getAgainLoading({ parentId: data.id, xmId: data.xmId }).then(response => {
            this.data = response.data
            for (let i = 0; i < this.data.length; i++) {
              const newChild = this.data[i]
              if (!dataA.children) {
                this.$set(dataA, 'children', [])
              }
              dataA.children.push(newChild)
            }
            this.dataId = dataA.id
            this.IdArr.push(dataA.id)
            this.listLoading = false
          }).catch(response => {
            this.listLoading = false
          })
        }
      }
    },
    handleAdd() {
      this.dialogAddVisible = true
      this.$nextTick(() => {
        this.$refs.dialogAdd
      })
    },
    handleEdit() {
      this.dialogEditVisible = true
      this.code = this.classifyId
      this.$nextTick(() => {
        this.$refs.dialogEdit
      })
    },
    add() {
      if (this.parent === '-1') {
        Message({
          message: '请选择子节点！',
          type: 'error',
          duration: 5 * 1000
        })
      } else if (this.parent !== '-1' && this.flag !== 'WD') {
        if (this.xiangmuId !== null && this.xiangmuId !== '') {
          if (this.classifyId !== null && this.classifyId !== '') {
            this.addApiVisible = true
            this.$nextTick(() => {
              this.$refs.addApi
            })
          } else {
            Message({
              message: '请选择节点！',
              type: 'error',
              duration: 5 * 1000
            })
          }
        } else {
          Message({
            message: '请选择项目！',
            type: 'error',
            duration: 5 * 1000
          })
        }
      }
    },
    edit() {
      if (this.parent !== '-1' && this.flag === 'WD') {
        if (this.xiangmuId !== null && this.xiangmuId !== '') {
          if (this.classifyId !== null && this.classifyId !== '') {
            this.editApiVisible = true
            this.$nextTick(() => {
              this.$refs.editApi
            })
          } else {
            Message({
              message: '请选择子节点！',
              type: 'error',
              duration: 5 * 1000
            })
          }
        } else {
          Message({
            message: '请选择项目！',
            type: 'error',
            duration: 5 * 1000
          })
        }
      } else {
        Message({
          message: '请选择文档节点！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    history() {
      if (this.parent !== '-1' && this.flag === 'WD') {
        if (this.xiangmuId !== null && this.xiangmuId !== '') {
          if (this.classifyId !== null && this.classifyId !== '') {
            this.historyVisible = true
            this.$nextTick(() => {
              this.$refs.history
            })
          } else {
            Message({
              message: '请选择子节点！',
              type: 'error',
              duration: 5 * 1000
            })
          }
        } else {
          Message({
            message: '请选择项目！',
            type: 'error',
            duration: 5 * 1000
          })
        }
      } else {
        Message({
          message: '请选择文档节点！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    download() {
      if (this.xiangmuId !== null && this.xiangmuId !== '') {
        this.downloadVisible = true
        this.$nextTick(() => {
          this.$refs.download
        })
      } else {
        Message({
          message: '请选择项目！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    handleDisable() {
      MessageBox.confirm('确认删除节点', '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disabled(this.NODE.id).then(response => {
          Message({
            message: '删除节点成功',
            type: 'success',
            duration: 5 * 1000
          })
          // 重新加载表格
          this.getTreeList(this.xiangmuId)
        })
      })
    },
    remove() {
      if (this.parent !== '-1' && this.flag === 'WD') {
        if (this.xiangmuId !== null && this.xiangmuId !== '') {
          if (this.classifyId !== null && this.classifyId !== '') {
            MessageBox.confirm('确认删除', '确定', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              remove({ code: this.classifyId }).then(response => {
                Message({
                  message: '删除成功',
                  type: 'success',
                  duration: 5 * 1000
                })
                // 重新加载表格
                this.getTreeList(this.xiangmuId)
                // 重新加载表格
                this.handleNodeClick()
              })
            })
          } else {
            Message({
              message: '请选择子节点！',
              type: 'error',
              duration: 5 * 1000
            })
          }
        } else {
          Message({
            message: '请选择项目！',
            type: 'error',
            duration: 5 * 1000
          })
        }
      } else {
        Message({
          message: '请选择文档节点！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    yulan() {
      if (this.xiangmuId !== null && this.xiangmuId !== '') {
        this.yulanVisible = true
        this.$nextTick(() => {
          this.$refs.yulan
        })
      } else {
        Message({
          message: '请选择项目！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    }
  }
}
</script>

<style scoped>
.app-container{
    height:calc(100% - 20px) !important;
    width:calc(100% - 20px) !important;
    padding:10px 0;
}
#app-contain{
  height:100%;
  width:100%
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
/* 右键会选中文字，为了美观将它禁用*/
#el-tree{
  user-select:none;
}
#el-tree >>> .style-demo {
  color: #474a4d;
  font-size: 14px;
  font-family: "黑体";
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.menu1 {
  height: 40px;
  width: 120px;
  position: fixed;
  border: 1px solid #ccc;
  background-color: white;
  list-style: none;
  padding-left: 10px;
}
.menu2 {
  height: 100px;
  width: 120px;
  position: fixed;
  border: 1px solid #ccc;
  background-color: white;
  list-style: none;
  padding-left: 10px;
}
.menu_item {
  line-height: 20px;
  text-align: left;
  margin-top: 10px;
}
.collapse-title{
  font-size: 16px;
  color:#1196EE;
}
.table{
  border-collapse: separate;
  border-spacing: 10px 10px;
}
.title-name{
  width: 100px;
  text-align: left;
  vertical-align: middle;
}
.table-content{
  width: 450px;
}

</style>
